package com.reger.l2cache.pipeline.pipe;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

import com.reger.l2cache.pipeline.core.PipelineCore;

public class IntegerRedisPipeline extends RedisPipeline<String, String, Integer> {

	private static final Logger log = LoggerFactory.getLogger(IntegerRedisPipeline.class);
	private final RedisSerializer<Integer> integerRedisSerializer = new RedisSerializer<Integer>() {

		@Override
		@SuppressWarnings("unchecked")
		public byte[] serialize(Integer t) throws SerializationException {
			if (t == null) {
				return null;
			}
			return stringSerializer.serialize(String.valueOf(t));
		}

		@Override
		public Integer deserialize(byte[] bytes) throws SerializationException {
			String numStr = (String) stringSerializer.deserialize(bytes);
			if (numStr == null) {
				return null;
			}
			try {
				return Integer.parseInt(numStr);
			} catch (Exception e) {
				log.warn("数据{}转化为Integer类型失败,", numStr, e);
				return null;
			}
		}
	};

	@SuppressWarnings("unchecked")
	public IntegerRedisPipeline(PipelineCore pipelineCore) {
		super(pipelineCore);
		this.setKeySerializer(stringSerializer);
		this.setHashKeySerializer(stringSerializer);
		this.setValueSerializer(integerRedisSerializer);
	}
}
